/*
 * @Date: 2023-08-08 16:18:36
 * @LastEditors: lyx
 * @LastEditTime: 2023-12-04 16:32:19
 * @FilePath: \sup-mini-app\src\pages\index\hooks\useHome.tsx
 * @Descriptio:
 */
import React, { useEffect, useState } from "react";
import jump from "@/utils/jump";
import { queryPostList } from "@/services/post";
import Taro, { requirePlugin } from "@tarojs/taro";
import { TEMPLATE_PROCESS_TO_DO_REMINDERS } from "@/utils/weapp";
import { useSetState } from "ahooks";
//引入插件：微信同声传译
const plugin = requirePlugin("WechatSI");
//获取全局唯一的语音识别管理器recordRecoManager
const manager = plugin.getRecordRecognitionManager();

function useHome() {
  const [postList, setPostList] = useState<IPostItem[]>([]);
  const [inputState, setInputState] = useSetState<{
    inputValue: string;
    recordState: boolean;
  }>({
    inputValue: "",
    recordState: false,
  });

  const handleClick = (menu) => {
    console.log("menu", menu);
    if (menu.key === "gpt") {
      jump({ url: menu.url, title: menu.text });
    }
  };

  const getPostList = async () => {
    const { status, content = {}, msg = "" } = await queryPostList({});
    if (status) {
      const { records = [] } = content;
      setPostList(records);
    } else {
      console.log(msg);
    }
  };

  /**
   * @description:获取下发权限
   * @return {*}
   */
  const requestSubscribe = () => {
    Taro.requestSubscribeMessage({
      tmplIds: [TEMPLATE_PROCESS_TO_DO_REMINDERS.template_id],
      success(res) {
        console.log(res, "res");
        // handleLogin();
      },
    });
  };

  const initRecord = () => {
    manager.onRecognize = (res) => {
      console.log(res);
    };
    manager.onStart = (res) => {
      setInputState({
        recordState: true,
      });
      console.log("成功开始录音识别", res);
    };
    manager.onError = (res) => {
      console.error("录音识别 error", res);
    };
    manager.onStop = (res) => {
      console.log("..............结束录音");
      console.log("录音临时文件地址 -->" + res.tempFilePath);
      console.log("录音总时长 -->" + res.duration + "ms");
      console.log("文件大小 --> " + res.fileSize + "B");
      console.log("语音内容 --> " + res.result);
      if (res.result == "") {
        Taro.showModal({
          title: "提示",
          content: "听不清楚，请重新说一遍！",
          showCancel: false,
          success: function (res) {},
        });
        return;
      }
      const text = inputState.inputValue + res.result;
      setInputState({
        inputValue: text,
        recordState: false,
      });
    };
  };

  const touchStart = () => {
    setInputState({
      recordState: true, //录音状态
    });
    // 语音开始识别
    manager.start({
      lang: "zh_CN", // 识别的语言，目前支持zh_CN en_US zh_HK sichuanhua
    });
  };
  const touchEnd = () => {
    setInputState({
      recordState: false, //录音状态
    });
    // 语音结束识别
    manager.stop();
  };

  useEffect(() => {
    Taro.getStorage({
      key: "phoneNumber",
      success: function (res) {
        console.log("phoneNumber res", res);
        console.log("phoneNumber", res.data);
      },
    });
    Taro.showModal({
      title: "温馨提示",
      content:
        "为更好的促进消息更新，服务号需要在您的任务消息更新时向您发送消息",
      confirmText: "同意",
      cancelText: "拒绝",
      success: function (res) {
        if (res.confirm) {
          //调用订阅消息
          console.log("用户点击确定");
          //调用订阅
          requestSubscribe();
        } else if (res.cancel) {
          console.log("用户点击取消");
          ///显示第二个弹说明一下
          Taro.showModal({
            title: "温馨提示",
            content: "拒绝后您将无法获取实时的任务消息",
            confirmText: "知道了",
            showCancel: false,
            success: function (res) {
              ///点击知道了的后续操作
              ///如跳转首页面
            },
          });
        }
      },
    });
    initRecord();

    getPostList();
  }, []);

  return {
    postList,
    inputState,
    handleClick,
    setInputState,
    touchStart,
    touchEnd,
  };
}

export default useHome;
